/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.lecture.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import vip.xiaonuo.biz.modular.course.entity.EduCourse;
import vip.xiaonuo.biz.modular.course.service.EduCourseService;
import vip.xiaonuo.biz.modular.lecture.enums.EduLectureStateEnum;
import vip.xiaonuo.biz.modular.room.enums.EduRoomTypeEnum;
import vip.xiaonuo.biz.modular.timetable.service.TimetableService;
import vip.xiaonuo.biz.modular.lecture.param.*;
import vip.xiaonuo.biz.modular.teacher.entity.EduTeacher;
import vip.xiaonuo.biz.modular.teacher.service.EduTeacherService;
import vip.xiaonuo.biz.modular.tutorial.entity.EduTutorial;
import vip.xiaonuo.biz.modular.tutorial.enums.EduTutorialEnum;
import vip.xiaonuo.biz.modular.tutorial.enums.EduTutorialStateEnum;
import vip.xiaonuo.biz.modular.tutorial.param.EduTutorialExportParam;
import vip.xiaonuo.biz.modular.tutorial.service.EduTutorialService;
import vip.xiaonuo.common.annotation.CommonLog;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.common.pojo.CommonValidList;
import vip.xiaonuo.biz.modular.lecture.entity.EduLecture;
import vip.xiaonuo.biz.modular.lecture.service.EduLectureService;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 开课控制器
 *
 * @author ahui
 * @date  2023/05/13 21:21
 */
@Api(tags = "开课控制器")
@ApiSupport(author = "SNOWY_TEAM", order = 1)
@RestController
@Validated
public class EduLectureController {

    @Resource
    private EduLectureService eduLectureService;

    @Resource
    private EduTutorialService eduTutorialService;

    @Resource
    private EduTeacherService eduTeacherService;

    @Resource
    private EduCourseService eduCourseService;

    @Resource
    private TimetableService timetableService;

    /**
     * 获取开课分页
     *
     * @author ahui
     * @date  2023/05/13 21:21
     */
    @ApiOperationSupport(order = 1)
    @ApiOperation("获取开课分页")
    @SaCheckPermission("/biz/lecture/page")
    @GetMapping("/biz/lecture/page")
    public CommonResult<Page<EduLecture>> page(EduLecturePageParam eduLecturePageParam) {
        return CommonResult.data(eduLectureService.page(eduLecturePageParam));
    }

    /**
     * 添加开课
     *
     * @author ahui
     * @date  2023/05/13 21:21
     */
    @ApiOperationSupport(order = 2)
    @ApiOperation("添加开课")
    @CommonLog("添加开课")
    @SaCheckPermission("/biz/lecture/add")
    @PostMapping("/biz/lecture/add")
    public CommonResult<String> add(@RequestBody @Valid EduLectureAddParam eduLectureAddParam) {
        eduLectureService.add(eduLectureAddParam);
        return CommonResult.ok();
    }

    /**
     * 编辑开课
     *
     * @author ahui
     * @date  2023/05/13 21:21
     */
    @ApiOperationSupport(order = 3)
    @ApiOperation("编辑开课")
    @CommonLog("编辑开课")
    @SaCheckPermission("/biz/lecture/edit")
    @PostMapping("/biz/lecture/edit")
    public CommonResult<String> edit(@RequestBody @Valid EduLectureEditParam eduLectureEditParam) {
        eduLectureService.edit(eduLectureEditParam);
        return CommonResult.ok();
    }

    /**
     * 删除开课
     *
     * @author ahui
     * @date  2023/05/13 21:21
     */
    @ApiOperationSupport(order = 4)
    @ApiOperation("删除开课")
    @CommonLog("删除开课")
    @SaCheckPermission("/biz/lecture/delete")
    @PostMapping("/biz/lecture/delete")
    public CommonResult<String> delete(@RequestBody @Valid @NotEmpty(message = "集合不能为空")
                                                   CommonValidList<EduLectureIdParam> eduLectureIdParamList) {
        eduLectureService.delete(eduLectureIdParamList);
        return CommonResult.ok();
    }

    /**
     * 获取开课详情
     *
     * @author ahui
     * @date  2023/05/13 21:21
     */
    @ApiOperationSupport(order = 5)
    @ApiOperation("获取开课详情")
    @SaCheckPermission("/biz/lecture/detail")
    @GetMapping("/biz/lecture/detail")
    public CommonResult<EduLecture> detail(@Valid EduLectureIdParam eduLectureIdParam) {
        return CommonResult.data(eduLectureService.detail(eduLectureIdParam));
    }

    /**
     * 获取教师选择器
     * @return ahui
     * * @date  2023/05/13 21:39
     */
    @ApiOperationSupport(order = 6)
    @ApiOperation("获取教师选择器")
    //@SaCheckPermission("/biz/lecture/teacherList")
    @GetMapping("/biz/lecture/teacherList")
    public CommonResult<List<EduTeacher>> teacherSelector() {
        return CommonResult.data(eduTeacherService.list());
    }


    /**
     * 获取课程选择器
     * @return ahui
     * * @date  2023/05/13 21:39
     */
    @ApiOperationSupport(order = 7)
    @ApiOperation("获取课程选择器")
    //@SaCheckPermission("/biz/lecture/courseList")
    @GetMapping("/biz/lecture/courseList")
    public CommonResult<List<EduCourse>> courseSelector() {
        return CommonResult.data(eduCourseService.list());
    }

    /**
     * 一键排课
     */
    @ApiOperationSupport(order = 8)
    @ApiOperation("一键排课")
    @CommonLog("一键排课")
    @GetMapping("/biz/lecture/smartExport")
    public CommonResult<String> smartExport(EduLectureExportParam eduLectureExportParam) {
        List<EduLecture> lectures = eduLectureService.listByIds(StrUtil.split(eduLectureExportParam.getLectureIds(), StrUtil.COMMA));
        for (EduLecture lecture: lectures) {
            if (ObjectUtil.isEmpty(lecture.getTeacherId())) {
                return CommonResult.error("开课记录中教师不能为空");
            }
            if (ObjectUtil.isEmpty(lecture.getFromWeek())) {
                return CommonResult.error("开课记录中开始周不能为空");
            }
            if (ObjectUtil.isEmpty(lecture.getToWeek())) {
                return CommonResult.error("开课记录中结束周不能为空");
            }
        }
        timetableService.process(eduLectureExportParam.getLectureIds());
        return CommonResult.ok();
    }

    /**
     * 统计课时
     */
    @ApiOperationSupport(order = 8)
    @ApiOperation("统计课时")
    @CommonLog("统计课时")
    @GetMapping("/biz/lecture/calculate")
    public CommonResult<String> calculate(EduLectureExportParam eduLectureExportParam) {
        List<EduLecture> lectures = eduLectureService.listByIds(StrUtil.split(eduLectureExportParam.getLectureIds(), StrUtil.COMMA));
        Map<String, Integer> teacherClassHour = new HashMap();
        for (EduLecture lecture: lectures) {
            String teacherId = lecture.getTeacherId();
            EduCourse eduCourse = eduCourseService.getById(lecture.getCourseId());
            if (teacherClassHour.containsKey(teacherId)) {
                teacherClassHour.put(teacherId, teacherClassHour.get(teacherId) + eduCourse.getClassHour());
            } else {
                teacherClassHour.put(teacherId, eduCourse.getClassHour());
            }
        }
        List<EduTeacher> teachers = eduTeacherService.listByIds(teacherClassHour.keySet());
        for (EduTeacher teacher: teachers) {
            teacher.setClassHour(teacherClassHour.get(teacher.getId()));
        }
        eduTeacherService.updateBatchById(teachers);
        return CommonResult.ok();
    }

    /**
     * 创建开课
     *
     */
    @ApiOperationSupport(order = 9)
    @ApiOperation("创建开课")
    @CommonLog("创建开课")
    @GetMapping(value = "/biz/lecture/create")
    public CommonResult<String> create(EduLectureCreateParam eduLectureCreateParam){
        List<String> tutorialIds = StrUtil.split(eduLectureCreateParam.getTutorialIds(), StrUtil.COMMA);
        for (String tutorialId: tutorialIds) {
            EduTutorial tutorial = eduTutorialService.getById(tutorialId);
            if (EduTutorialStateEnum.DONE.getValue().equals(tutorial.getState())) {
                continue;
            }
            EduLecture eduLecture = new EduLecture();
            eduLecture.setCourseId(tutorial.getCourseId());
            eduLecture.setSize(tutorial.getSize());
            eduLecture.setKlasses(JSONUtil.toJsonStr(new String[] {tutorial.getKlassId()}));
            eduLecture.setFromWeek(tutorial.getFromWeek());
            eduLecture.setToWeek(tutorial.getToWeek());
            eduLecture.setRoomType(EduRoomTypeEnum.NONSPECIFIC.getValue());
            eduLecture.setState(EduLectureStateEnum.DOING.getValue());
            eduLectureService.save(eduLecture);

            tutorial.setLectureId(eduLecture.getId());
            tutorial.setState(EduTutorialStateEnum.DONE.getValue());
            eduTutorialService.updateById(tutorial);
        }
        return CommonResult.ok();
    }

    /**
     * 合班开课
     *
     * @author xuyuxiang
     * @date 2022/4/24 20:00
     */
    @ApiOperationSupport(order = 9)
    @ApiOperation("合班开课")
    @CommonLog("合班开课")
    @GetMapping(value = "/biz/lecture/merge")
    public CommonResult<String> merge(EduTutorialExportParam eduTutorialExportParam){
        List<String> tutorialIds = StrUtil.split(eduTutorialExportParam.getTutorialIds(), StrUtil.COMMA);
        List<EduTutorial> tutorials = eduTutorialService.listByIds(tutorialIds);
        EduLecture eduLecture = new EduLecture();
        eduLecture.setCourseId(tutorials.get(0).getCourseId());
        int size = 0;
        List<String> klassIds = new ArrayList<>();
        for (EduTutorial tutorial: tutorials) {
            size += tutorial.getSize();
            klassIds.add(tutorial.getKlassId());
            if (!tutorial.getCourseId().equals(eduLecture.getCourseId())) {
                return CommonResult.error("不同课程无法合班开课");
            }
        }
        eduLecture.setSize(size);
        eduLecture.setKlasses(JSONUtil.toJsonStr(klassIds));
        eduLecture.setFromWeek(tutorials.get(0).getFromWeek());
        eduLecture.setToWeek(tutorials.get(0).getToWeek());
        eduLecture.setState(EduLectureStateEnum.DOING.getValue());
        eduLecture.setRoomType(EduRoomTypeEnum.NONSPECIFIC.getValue());
        eduLectureService.save(eduLecture);
        for (EduTutorial tutorial: tutorials) {
            tutorial.setLectureId(eduLecture.getId());
            tutorial.setState(EduTutorialStateEnum.DONE.getValue());
            tutorial.setCombineClass(true);
            eduTutorialService.updateById(tutorial);
        }
        return CommonResult.ok();
    }
}
